package com.youjiang.meeting.controller;

import java.io.File;
import java.io.IOException;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Random;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.youjiang.meeting.mapper.OrdersMapper;
import com.youjiang.meeting.mapper.SaveQrUrlMapper;
import com.youjiang.meeting.mapper.WxconfigMapper;
import com.youjiang.meeting.po.Expire;
import com.youjiang.meeting.po.Orders;
import com.youjiang.meeting.po.OrdersExample;
import com.youjiang.meeting.po.Program;
import com.youjiang.meeting.po.SaveQrUrl;
import com.youjiang.meeting.po.SaveQrUrlExample;
import com.youjiang.meeting.po.UserInfo;
import com.youjiang.meeting.po.Wxconfig;
import com.youjiang.meeting.po.WxconfigExample;
import com.youjiang.meeting.service.UserService;
import com.youjiang.meeting.service.WeiXinMassegeService;
import com.youjiang.meeting.utils.ToolUtils;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

@Controller
@RequestMapping(value = "/management")
public class UserController {
	
	@Autowired
	private UserService userService;
	@Autowired
	private WeiXinMassegeService weiXinService;
	@Autowired 
	private WxconfigMapper configMapper;
	@Autowired
	private OrdersMapper oMapper;
	@Autowired
	private SaveQrUrlMapper sqMapper;

	
	
	@RequestMapping(value="/register",method ={RequestMethod.POST},produces = "application/json; charset=utf-8")
	@ResponseBody
	public String register(UserInfo info) throws ParseException{
		JSONObject json=new JSONObject();
		if(StringUtils.isEmpty(info.getEmail())){
			json.put("code", 1);
			json.put("msg", "邮箱不能为空");
			return json.toString();
		}
		if(StringUtils.isEmpty(info.getPassword())){
			json.put("code", 1);
			json.put("msg", "密码不能为空");
			return json.toString();
		}
		if(StringUtils.isEmpty(info.getName())){
			json.put("code", 1);
			json.put("msg", "公司名不能为空");
			return json.toString();
		}
		boolean flag = userService.findByEmail(info.getEmail());
		if(!flag){
			json.put("code", 1);
			json.put("msg", "邮箱已经注册，请换一个邮箱注册");
			return json.toString();
		}
		
		boolean isFlag = userService.register(info.getEmail(), info.getPassword(), info.getName());
		/**
		 * 用户注册成功
		 */
		if(isFlag){
			Date beginDate = new Date();	
			Calendar date = Calendar.getInstance();
			date.setTime(beginDate);
			DateFormat dft = new SimpleDateFormat("yyyy-MM-dd");
			date.set(Calendar.DATE, date.get(Calendar.DATE) +15);
			Date endDate = dft.parse(dft.format(date.getTime()));
			String time = dft.format(endDate);
			UserInfo userInfo = userService.findUserInfoByEmail(info.getEmail());
			if(userInfo!=null){
				System.out.println("用户注册成功");
				userService.insertResgisterTime(userInfo.getId(), time);
				json.put("code", 0);
				json.put("msg", "注册成功");
				return json.toString();
			}
			json.put("code", 1);
			json.put("msg", "注册失败");
			return json.toString();
		}
		json.put("code", 1);
		json.put("msg", "注册失败");
		return json.toString();		
	}
	

	@RequestMapping(value="/login",method ={RequestMethod.POST},produces = "application/json; charset=utf-8")
	@ResponseBody
	public String login(HttpSession httpSession,String email,String password){
		JSONObject json=new JSONObject();
		System.out.println(email+"---"+password);
		UserInfo userInfo = userService.login(email, password);
		if(userInfo==null){
			json.put("code", 00);
			json.put("msg", "用户登录失败");
			return json.toString();
		}else{
			httpSession.setAttribute("userInfo", userInfo);
			ToolUtils.sessions.put(userInfo.getId(), httpSession);
			Map<Integer, HttpSession> map = ToolUtils.sessions;
			for(Map.Entry<Integer, HttpSession> entry:map.entrySet()){
				System.out.println(entry.getKey()+">>>"+entry.getValue().getAttribute("userInfo")+">>"+entry.getValue().getMaxInactiveInterval());
			}
			System.out.println("*********************");
			int userid = userInfo.getId();
			Wxconfig config = userService.getWxconfigByUserId(userid);
			if(config==null){
				json.put("code", 11);
				json.put("msg", "配置项为空....");
			}else{			
				json.put("code", 12);
				json.put("msg", "配置项存在....");
			}	
			return json.toString();		
	   }
	}
	
	@RequestMapping(value="/checkExpire",method ={RequestMethod.POST},produces = "application/json; charset=utf-8")
	@ResponseBody
	public String checkExpire(HttpSession httpSession) throws ParseException{
		JSONObject json=new JSONObject();
		UserInfo info = (UserInfo) httpSession.getAttribute("userInfo");
		//json.put("info", "用户信息:"+info);
		if(info!=null){
			int id = info.getId();
			Expire in = userService.getExpireInByUserId(info.getId());
			if(in!=null){
				String expireTime = in.getExpireIn();//2017-7-20
				Date nowdate = new Date();         //2017-7-21
				SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd", Locale.CHINA);
				Date d = sdf.parse(expireTime);
				String now = sdf.format(nowdate);
				Date ntime = sdf.parse(now);
				boolean flag = d.before(nowdate);
				System.out.println("flag-----------"+flag);
				if(flag){
					json.put("code", 0);
					OrdersExample example = new OrdersExample();
					OrdersExample.Criteria criteria = example.createCriteria();
					criteria.andUseridEqualTo(info.getId());
					
					List<Orders> orderList = oMapper.selectByExample(example);
					System.out.println("orderList--->"+orderList.size());
					if(orderList!=null && orderList.size()>0){
						//一个用户有多个订单，因此要获取最后支付成功的那个订单的状态
						int maxOrderId = oMapper.findMaxOrderIdByOrderStatus(1);
						System.out.println("maxOrderId--->"+maxOrderId);
						if(maxOrderId>0){
							json.put("msg", "1年的有效期已过,请充值消费");	
						}
						
					}else{
						json.put("msg", "15天的有效期已过,请充值消费");	
					}
					
					return json.toString();
				}else{
					long syDay = d.getTime()-ntime.getTime();
					long syts = syDay/60/60/1000/24;//获取今天到指定日期剩余天数
					if(syts>0){
						json.put("code", 1);
						json.put("msg", syts);	
						return json.toString();
					}				
				}
			}
		}
		json.put("code", 00);
		json.put("msg", "登录超时,请重新登录");	
		return json.toString();		
	}
	
	@SuppressWarnings("unused")
	@RequestMapping(value="/activityInfo",method ={RequestMethod.POST},produces = "application/json; charset=utf-8")
	@ResponseBody
	public String activityInfo(HttpSession session){
		JSONObject json=new JSONObject();
		UserInfo userInfo = (UserInfo) session.getAttribute("userInfo");
		if(userInfo==null){
	    	json.put("code", 0);
	    	json.put("msg", "登录超时，请重新登录");
	    	return json.toString();
	    }
	    List<Program> activities = userService.getProgramsByUserId(1);
	    if(activities==null){
	    	json.put("code", 0);
	    	json.put("msg", "跳转至配置页");
	    	return json.toString();
	    }
	    JSONArray array = JSONArray.fromObject(activities);	 
	    
	    json.put("code", 1);
    	json.put("msg", array.toString());
    	return json.toString();
	}
	
	@RequestMapping(value="/readConfig",method ={RequestMethod.POST},produces = "application/json; charset=utf-8")
	@ResponseBody
	public String configure(HttpSession session){
		JSONObject json=new JSONObject();
		UserInfo userInfo = (UserInfo) session.getAttribute("userInfo");
		if(userInfo==null){
	    	json.put("code", 00);
	    	json.put("msg", "登录超时，请重新登录");
	    	return json.toString();
	    }
		Wxconfig wxconfig = userService.getWxconfigByUserId(userInfo.getId());
		if(wxconfig==null){
			json.put("code", 01);
	    	json.put("msg", "配置信息为空");
	    	return json.toString();
		}
		
		json.put("code", 1);
    	json.put("msg", "配置信息存在");
    	return json.toString();
	}
	
	
	
	@RequestMapping(value="/writeConfigure",method ={RequestMethod.POST},produces = "application/json; charset=utf-8")
	@ResponseBody
	public String WriteConfigure(HttpSession session,Wxconfig config){
		JSONObject json=new JSONObject();
		if(config.getAppid()==null){
			return ToolUtils.json(json, "0", "appid不能为空");
		}
		if(config.getApsecrect()==null){
			return ToolUtils.json(json, "0", "appsecrect不能为空");
		}
		if(config.getName()==null){
			return ToolUtils.json(json, "0", "公众号不能为空");
		}
		UserInfo userInfo = (UserInfo) session.getAttribute("userInfo");
		if(userInfo==null){
			
	    	json.put("code", 00);
	    	json.put("msg", "登录超时，请重新登录");
	    	return json.toString();
	    }
		
		config.setUserid(userInfo.getId());
		System.out.println("--------------------------------"+"执行到这里");
        try{
        	userService.writeConfigure(config);
        }catch(Exception e){
        	System.out.println("--------------------------------"+"执行有误");
        	e.printStackTrace();
        }
        System.out.println("--------------------------------"+"执行成功");
		json.put("code", 1);
    	json.put("msg", "写入配置页成功");
    	return json.toString();		
	}
	
	@RequestMapping(value="/updateConfig",method ={RequestMethod.POST},produces = "application/json; charset=utf-8")
	@ResponseBody
	public String updateConfigure(HttpSession session,Wxconfig config){
		JSONObject json=new JSONObject();
		UserInfo userInfo = (UserInfo) session.getAttribute("userInfo");
		if(userInfo==null){
	    	json.put("code", 00);
	    	json.put("msg", "登录超时，请重新登录");
	    	return json.toString();
	    }
		config.setUserid(userInfo.getId());
		userService.updateConfigure(config);
		json.put("code", 1);
    	json.put("msg", "更新成功");
    	return json.toString();
	}
	
	@RequestMapping(value="/order",method ={RequestMethod.POST},produces = "application/json; charset=utf-8")
	@ResponseBody
	public String order(HttpSession session){
		JSONObject json = new JSONObject();
		UserInfo userInfo = (UserInfo) session.getAttribute("userInfo");
		if(userInfo==null){
			json.put("code", 00);
			json.put("msg", "当前用户登录过期，请重新登录");
			return json.toString();
		}
		
		return null;	
	}
	
	/**
	 * 根据用户id得到公众号名originid
	 * @param session
	 * @return
	 */
	@RequestMapping(value="/getMsgByWebS",method ={RequestMethod.POST},produces = "application/json; charset=utf-8")
	@ResponseBody
	public String getMsgByWebS(HttpSession session){
        
		JSONObject object = new JSONObject();
		
		UserInfo userInfo = (UserInfo) session.getAttribute("userInfo");
		System.out.println("userInfo------->"+userInfo);
		
		if(userInfo==null){
			return ToolUtils.json(object, "00", "当前用户登录过期，请重新登录");
		}
		String originid = null;
		WxconfigExample example = new WxconfigExample();
		WxconfigExample.Criteria criteria = example.createCriteria();
		criteria.andUseridEqualTo(userInfo.getId());
		List<Wxconfig> configList = configMapper.selectByExample(example);
	    if(configList!=null && configList.size()>0){
	    	Wxconfig config = configList.get(0);
	    	originid = config.getOriginid();
	    	return ToolUtils.json(object, "01", originid);
	    }
		return ToolUtils.json(object, "02", "请联系管理员确认公众号是否配置正确");
		
	}
	
	@ResponseBody
	@RequestMapping(value = "/photoUpload",method = RequestMethod.POST,produces = "application/json; charset=utf-8")
	public String pictureUpload(MultipartFile file,HttpServletRequest request,
			HttpServletResponse response,HttpSession session){
		JSONObject object = new JSONObject();
		UserInfo userInfo = (UserInfo) session.getAttribute("userInfo");
		if(userInfo==null){
			return ToolUtils.json(object, "00", "当前用户登录过期，请重新登录");
		}
		if(file!=null){
			String path=null;// 文件路径
			String type=null;// 文件类型
			String fileName=file.getOriginalFilename();// 文件原名称
			System.out.println("上传的文件原名称:"+fileName);
			// 判断文件类型
			type=fileName.indexOf(".")!=-1?fileName.substring(fileName.lastIndexOf(".")+1, 
					fileName.length()):null;
			if (type!=null) {// 判断文件类型是否为空
				if ("GIF".equals(type.toUpperCase())||"PNG".equals(type.toUpperCase())||"JPG".equals(type.toUpperCase())) {
					// 项目在容器中实际发布运行的根路径
					String realPath=request.getSession().getServletContext().getRealPath("/");
					// 自定义的文件名称
					String trueFileName=String.valueOf(new Random().nextInt(10))+fileName;
					// 设置存放图片文件的路径
					path=realPath+trueFileName;
					
					System.out.println("存放图片文件的路径:"+path);
					// 转存文件到指定的路径
					try {
						file.transferTo(new File(path));
					} catch (IllegalStateException | IOException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
						return ToolUtils.json(object, "05", "请重新上传");
					}
					System.out.println("文件成功上传到指定目录下");
					SaveQrUrlExample example = new SaveQrUrlExample();
					SaveQrUrlExample.Criteria criteria = example.createCriteria();
					criteria.andUseridEqualTo(userInfo.getId());
					List<SaveQrUrl> sqUrlList = sqMapper.selectByExample(example);
					System.out.println("sqUrlList--->"+sqUrlList.size());
					//更新公众号的二维码的url
					if(sqUrlList!=null && sqUrlList.size()>0){
						SaveQrUrl url = sqUrlList.get(0);
						String urlPath = url.getUrl();
						url.setUrl("http://119.23.71.112/meeting/"+trueFileName);
						sqMapper.updateByPrimaryKey(url);
						System.out.println("urlPath--->"+urlPath);
					}else{
						//如果之前公众号没有上传二维码则将该二维码的url保存到数据库中
						SaveQrUrl saveQrUrl = new SaveQrUrl();
						
						saveQrUrl.setUserid(userInfo.getId());
						saveQrUrl.setUrl("http://119.23.71.112/meeting/"+trueFileName);
						sqMapper.insert(saveQrUrl);
						System.out.println("path--->"+path);
					}
					/**
					 * 
					 * 上传成功
					 * 
					 */
					System.out.println("文件上传成功");
					return ToolUtils.json(object, "01", "文件上传成功");
					
				 }else {
					System.out.println("不是我们想要的文件类型,请按要求重新上传");
					return ToolUtils.json(object, "02", "不是我们想要的文件类型,请按要求重新上传");
				 }
			}else {
				System.out.println("文件类型为空");
				return ToolUtils.json(object, "03", "文件类型为空");
			}
		}else {
			System.out.println("没有找到相对应的文件");
			return ToolUtils.json(object, "04", "没有找到相对应的文件");
		}
	}
	
	@RequestMapping(value = "/getQrUrl",method = RequestMethod.POST,produces = "application/json; charset=utf-8")
	@ResponseBody
	public String getQrUrlFromUserid(HttpSession session){
		JSONObject object = new JSONObject();
		
		UserInfo userInfo = (UserInfo) session.getAttribute("userInfo");
		System.out.println("userInfo------->"+userInfo);
		
		if(userInfo==null){
			return ToolUtils.json(object, "00", "当前用户登录过期，请重新登录");
		}
		System.out.println("userInfo.id--->"+userInfo.getId());
		SaveQrUrl save = userService.getQrUrlFromUserid(userInfo.getId()); 
		if(save!=null){
			String qrurl = save.getUrl();
			System.out.println("qrurl--->"+qrurl);
			/**
			 * 
			 * 将用户ID传递到微信墙那边
			 * 
			 */
			return ToolUtils.json(object, "10", qrurl);
		}
		return ToolUtils.json(object, "10", "");
	}
}	
